from selenium import webdriver
from time import sleep
import csv


def writecsv(item):
    with open("今题网全国02.csv", 'a', encoding="utf-8", newline='') as f:
        writer = csv.writer(f)
        # writer.writerow(['招工标题', '工种', '招工信息（描述）', '发布时间', '联系人', '联系电话', '省（工作所在地）', '市（工作所在地）', '县（工作所在地）'])
        try:
            writer.writerow(item)
        except:
            print("write error")


def getElement():
    driver = webdriver.Chrome(r'E:\Google\chromedriver.exe')  # 浏览器插件地址
    for i in range(3, 53):
        driver.get('https://job.jinti.com/jishi/')
        sleep(1)
        driver.find_element_by_xpath('//*[@id="div"]/div[' + str(i) + ']/div[1]/a').click()
        sleep(1)
        """//*[@id="div"]/div[27]/div[1]/a"""
        try:
            title_element = driver.find_element_by_xpath("/html/body/div[4]/div[1]/div[1]/div[1]/p")  # 工作名称
            title_text = title_element.text
            # &nbsp    空格的意思
            title_list = title_text.split(' ')
            title = title_list[1]
            first_title = title_list[0]

            types = driver.find_element_by_xpath(
                "/html/body/div[4]/div[1]/div[2]/div[1]/table/tbody/tr[1]/td[1]")  # 职能种类
            Types_text = types.text
            types_list = Types_text.split('：')
            typ = types_list[1]

            time = driver.find_element_by_xpath("/html/body/div[4]/div[1]/div[1]/div[1]/div/div[2]")  # 时间
            time_text = time.text
            time_list = time_text.split(' ')
            date = time_list[0]  # + " " + time_list[1]

            Recruitment = driver.find_element_by_xpath(
                "/html/body/div[4]/div[1]/div[2]/div[1]/table/tbody/tr[4]/td[1]")  # 地址（市，省）
            Recruitment_text = Recruitment.text
            Recruitment_text_list = Recruitment_text.split('：')
            Rec = Recruitment_text_list[1]
            Rec_title = Rec.split(' ')
            Rec1 = Rec_title[0]
            Rec2 = Rec_title[1]

            driver.find_element_by_xpath(
                '/html/body/div[4]/div[1]/div[2]/div[2]/p[1]/span[2]/a').click()  # 点击查看详情电话

            number = driver.find_element_by_xpath("/html/body/div[4]/div[1]/div[2]/div[2]/p[1]/span[1]")  # 联系电话
            number_text = number.text
            number_list = number_text.split('：')
            num = number_list[1]

            Working = driver.find_element_by_xpath("/html/body/div[4]/div[1]/div[2]/div[2]/p[2]")  # 工作地址
            Working_text = Working.text
            work_list = Working_text.split('：')
            work = work_list[1]

            Job = driver.find_element_by_xpath('//*[@id="pnl_jobdesc"]')  # 职位描述
            job_text = Job.text

            lists = [title, typ, job_text, date, first_title, num, Rec1, Rec2, work]
            print(lists)
            writecsv(lists)
        except:
            print('NoSuchElementException')
            continue

    driver.quit()


if __name__ == "__main__":
    getElement()
